package jdk8_new_features;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

public class CompletableFuturePractice {


    public static void main(String[] args) {
        Long totalNum = 0L;
        CompletableFuture<Long> task1 = CompletableFuture.supplyAsync(() -> {
            Long total100 = 0L;
            for(int i=0; i< 100; i++){
                total100 = total100 + i;
            }
            return total100;
        });

        CompletableFuture<Long> task2 = CompletableFuture.supplyAsync(() -> {
            Long total200 = 0L;
            for(int i=0; i< 100; i++){
                total200 = total200 + i;
            }
            return total200;
        });

        CompletableFuture<Long> task3 = CompletableFuture.supplyAsync(() -> {
            Long total300 = 0L;
            for(int i=0; i< 100; i++){
                total300 = total300 + i;
            }
            return total300;
        });

        //求和方式1
        CompletableFuture<Long> total12 = task1.thenCombine(task2, (t1, t2) -> t1 + t2);
        CompletableFuture<Long> total123 = total12.thenCombine(task3, (t1, t2) -> t1 + t2);
        try {
            totalNum = total123.get();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }

        //求和方式2
        CompletableFuture<Long> temTask = CompletableFuture.allOf(task1, task2, task3).thenApply(v -> {
            Long temTotal = task1.join() + task2.join() + task3.join();
            return temTotal;
        });

        totalNum = temTask.join();

        System.out.println("==== totalNum = " + totalNum);

    }
}
